<template>
  <div class="header">欢迎来到在线问诊</div>
  <div class="container">
    <div class="sidebar">
      <div class="status">当前状态：{{ state ? "你已连接上服务端" : "未连接" }}</div>
      <div class="input-group">
        <label>患者昵称：</label>
        <input placeholder="请输入好友昵称" v-model="target" />
      </div>
      <div class="input-group">
        <label>昵称(必填)：</label>
        <input placeholder="输入你的昵称" v-model="name" />
      </div>
      <div class="input-group">
        <label>WebSocket地址(必填)：</label>
        <input placeholder="WS地址" v-model="wsAddress" />
        <button @click="connectWebsocket" class="connect-btn">上线</button>
      </div>
      <button @click="messageList = []" class="clear-btn">清屏</button>
    </div>

    <div class="message-container">
      <div v-for="(item, index) in messageList" :key="index" class="message-item">
        <div class="message-meta" :class="{ 'self-message': item.self }">
          {{ item.self ? `私聊消息(${name})` : item.name }}
          <span class="timestamp">{{ item.time }}</span>
        </div>
        <div class="message-content">{{ item.message }}</div>
      </div>
    </div>
    <div class="input-area">
      <textarea placeholder="请输入发送内容" v-model="content" />
      <div class="button-group">
        <button @click="sendMessage(1)">发送好友消息</button>
        <button @click="sendMessage(2)">发送群消息</button>
        <button @click="openPrescription" class="prescription-btn">开处方</button>
        <button @click="startVideoCall" class="video-call-btn">
          <i class="el-icon-video-camera"></i>
          视频通话
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {userInfo} from "@/api/system/user.js";
import { getToken, setToken, removeToken } from '@/utils/auth'
import Cookies from "js-cookie";
import axios from "axios";
import { useRouter } from 'vue-router'

// 响应式状态
const target = ref('')
const name = ref('')
let userId = 1;
const messageList = ref([])
const wsAddress = ref('ws://localhost:1212')
const content = ref('')
const state = ref(false)
const websocket = ref(null)
const router = useRouter()

// 工具函数
const getNowDate = () => {
  const now = new Date()
  return now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

// 根据token获取登录用户id
// userInfo(userId).then(res => {
//   name.value = res.data.nickName
// })

// WebSocket处理
const connectWebsocket = () => {
  if (websocket.value?.readyState === WebSocket.OPEN) {
    alert("您已在线")
    return
  }

  // if (!name.value) {
  //   alert("请设置昵称")
  //   return
  // }

  try {
    websocket.value = new WebSocket(wsAddress.value)

    websocket.value.onopen = () => {
      state.value = true
      websocket.value.send(JSON.stringify({
        code: "10001",
        nickname: name.value
      }))
      joinGroup()
    }

    websocket.value.onmessage = (e) => {
      const data = JSON.parse(e.data)
      messageList.value.push({
        ...data,
        time: data.time || getNowDate(),
        self: data.nickname === name.value
      })
    }

    websocket.value.onerror = (e) => console.error("WebSocket错误:", e)
    websocket.value.onclose = (e) => state.value = false

  } catch (error) {
    console.error("连接失败:", error)
    alert("连接服务器失败")
  }
}

const sendMessage = (type) => {
  if (!content.value) {
    alert("消息内容不能为空")
    return
  }

  if (type === 1 && target.value === name.value) {
    alert('不能给自己发消息')
    return
  }

  const message = {
    code: "10002",
    nickname: name.value,
    content: content.value,
    target: target.value,
    type: type
  }

  websocket.value.send(JSON.stringify(message))
  content.value = ''
}

const joinGroup = () => {
  websocket.value.send(JSON.stringify({
    code: "10003",
    nickname: name.value
  }))
}

const openPrescription = () => {
  // TODO: 实现开处方功能
  alert('开处方功能开发中...')
}



const generateRoomId = () => {
  return '1235115';
};

// 获取或生成房间号（仅依赖 URL 参数）
const getOrGenerateRoomId = () => {
  const urlParams = new URLSearchParams(window.location.search);
  let roomId = urlParams.get('roomId');

  // 1. 如果 URL 中没有 roomId，生成并重定向到带参数的 URL
  if (!roomId) {
    roomId = generateRoomId();
    const newUrl = new URL(window.location.href);
    newUrl.searchParams.set('roomId', roomId);
    window.location.replace(newUrl.toString()); // 强制重定向到含 roomId 的 URL
    return roomId; // 此处的 return 仅在重定向前短暂生效
  }

  // 2. 直接返回 URL 中的 roomId
  return roomId;
};

// 跳转逻辑（固定使用 URL 中的 roomId）
const startVideoCall = () => {
  const roomId = getOrGenerateRoomId(); // 直接获取 URL 中的房间号

  // 动态判断目标环境（本地或局域网）
  const currentHost = window.location.hostname;
  const isLocal = currentHost === 'localhost' || currentHost === '127.0.0.1';
  const targetHost = isLocal ? 'localhost' : currentHost;

  // 构建跳转 URL（强制包含房间号）
  const url = new URL(`https://${targetHost}:8087/toMeeting`);
  url.searchParams.append('userId', name.value);
  url.searchParams.append('roomId', roomId);

  // 执行跳转
  window.location.href = url.toString();
};



</script>

<style scoped>
.header {
  font-size: 16px;
  text-align: center;
  padding: 12px;
  background: #f6f6f6;
  color: #333;
  border-bottom: 1px solid #e5e5e5;
  margin: 0;
  font-weight: normal;
}

.container {
  display: flex;
  border: none;
  margin: 0;
  border-radius: 0;
  overflow: hidden;
  background: #f6f6f6;
  height: 100vh;
}

.sidebar {
  width: 250px;
  padding: 15px;
  background: #f6f6f6;
  border-right: 1px solid #e5e5e5;
}

.input-group {
  margin: 12px 0;
}

.input-group label {
  display: block;
  margin-bottom: 6px;
  color: #666;
  font-size: 13px;
}

input, textarea {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #e5e5e5;
  border-radius: 3px;
  margin-top: 3px;
  transition: all 0.2s;
  font-size: 13px;
  background: #fff;
}

input:focus, textarea:focus {
  border-color: #1aad19;
  background: #fff;
  outline: none;
}

button {
  background: #1aad19;
  color: white;
  border: none;
  padding: 7px 12px;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 13px;
  width: 100%;
}

button:hover {
  background: #129611;
}

.message-container {
  flex: 1;
  padding: 15px;
  height: calc(100vh - 44px);
  overflow-y: auto;
  background: #f6f6f6;
}

.message-item {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  max-width: 60%;
}

.message-item.self {
  margin-left: auto;
  align-items: flex-end;
}

.message-meta {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
  color: #999;
  font-size: 12px;
  padding: 0 10px;
}

.message-content {
  color: #333;
  line-height: 1.4;
  font-size: 14px;
  padding: 10px 12px;
  background: #fff;
  border-radius: 3px;
  position: relative;
  word-break: break-all;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}

.self .message-content {
  background: #95ec69;
  color: #000;
}

.timestamp {
  color: #999;
  font-size: 12px;
  margin-left: 8px;
}

.input-area {
  width: 250px;
  padding: 15px;
  border-left: 1px solid #e5e5e5;
  background: #f6f6f6;
  display: flex;
  flex-direction: column;
}

textarea {
  height: 120px;
  resize: none;
  font-family: inherit;
  background: #fff;
  margin-bottom: 10px;
}

.button-group {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.prescription-btn {
  background: #1aad19;
}

.prescription-btn:hover {
  background: #129611;
}

.video-call-btn {
  background: #409EFF;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.video-call-btn:hover {
  background: #337ECC;
}

.video-call-btn i {
  font-size: 16px;
}

.status {
  padding: 6px 10px;
  background: #f0f9eb;
  border-radius: 3px;
  color: #1aad19;
  font-size: 13px;
  margin-bottom: 12px;
  text-align: center;
}

.connect-btn {
  margin-top: 6px;
  background: #1aad19;
}

.connect-btn:hover {
  background: #129611;
}

.clear-btn {
  background: #999;
  margin-top: 10px;
  font-size: 13px;
}

.clear-btn:hover {
  background: #888;
}
</style>